<template>
	<view class="address-list">

		<!-- 选择模式提示 -->
		<!-- <view class="select-tip" v-if="isSelectMode">
			<text>请选择收货地址（点击地址项选择，或使用下方功能管理地址）</text>
		</view> -->

		<!-- 地址列表 -->
		<view class="address-items">
			<view class="address-item" :class="{ 'select-mode': isSelectMode }" v-for="(item, index) in addressList" :key="index" @click="handleAddressClick(item)">
				<view class="content">
					<view class="user-info">
						<text class="name">{{item.realName}}</text>
						<text class="phone">{{item.phone}}</text>
					</view>
					<view class="address-line">{{item.province}}{{item.city}}{{item.district}}-{{item.detail}}</view>
				</view>
				<!-- 选择模式下的选择指示器 -->
			<!-- 	<view class="select-indicator" v-if="isSelectMode">
					<text class="select-arrow">›</text>
				</view> -->
				<view class="item-footer">
					<view class="left">
						<radio :checked="item.isDefault==='1'" color="#4cd080" @click.stop="setDefaultAddress(item)" />
						<text class="default-text">设为默认</text>
					</view>
					<view class="edit" @click.stop="editAddress(item)">
						<text>修改</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 底部添加按钮 -->
		<view class="add-btn" @click="showAddModal">
			<text>添加收货地址</text>
		</view>

		<!-- 添加/编辑地址模态框 -->
		<AddAddressModal 
			:visible="showModal" 
			:editData="editData" 
			@close="hideAddModal" 
			@save="handleSaveAddress" 
		/>
	</view>
</template>

<script>
	import AddAddressModal from '@/components/AddAddressModal.vue'
	import {
		listAddress,
		addAddress,
		updateAddress,
		editDefault
	} from '@/api/userAddress.js'
	import {
		mapGetters
	} from "vuex"

	export default {
		components: {
			AddAddressModal
		},
		computed: mapGetters(['name', 'userId']),
		data() {
			return {
				showModal: false,
				editData: null,
				addressList: [],
				isSelectMode: false // 新增：是否为选择模式
			}
		},
		onLoad(options) {
			// 检查是否为选择模式
			if (options.selectMode === 'true') {
				this.isSelectMode = true;
				// 设置页面标题
				uni.setNavigationBarTitle({
					title: '选择收货地址'
				});
			}
		},
		created() {
			this.queryAddressList()
		},
		methods: {
			navigateBack() {
				uni.navigateBack()
			},
			// 新增：处理地址点击事件
			handleAddressClick(item) {
				if (this.isSelectMode) {
					// 选择模式：返回选中的地址
					uni.navigateBack({
						success: () => {
							// 通过事件总线传递选中的地址
							uni.$emit('addressSelected', item);
						}
					});
				} else {
					// 非选择模式：可以编辑地址
					this.editAddress(item);
				}
			},
			editAddress(item) {
				// 设置编辑数据并显示模态框
				this.editData = item
				this.showModal = true
			},
			showAddModal() {
				this.editData = null // 清空编辑数据，进入添加模式
				this.showModal = true
			},
			hideAddModal() {
				this.showModal = false
				this.editData = null // 关闭时清空编辑数据
			},

			queryAddressList() {
				listAddress({
					userId: this.userId
				}).then(res => {
					this.addressList = res.rows
				})
			},
			handleSaveAddress(addressData) {
				// 判断是添加还是编辑
				const isEdit = !!addressData.id
				
				// 添加用户ID
				addressData.userId = this.userId
				
				// 调用相应的API
				const apiCall = isEdit ? updateAddress(addressData) : addAddress(addressData)
				
				apiCall.then(res => {
					if (res.code === 200) {
						uni.showToast({
							title: isEdit ? '修改成功' : '保存成功',
							icon: 'success'
						})
						// 刷新地址列表
						this.queryAddressList()
					} else {
						uni.showToast({
							title: res.msg || (isEdit ? '修改失败，请重试' : '保存失败，请重试'),
							icon: 'none'
						})
					}
				}).catch(err => {
					uni.showToast({
						title: isEdit ? '修改失败，请重试' : '保存失败，请重试',
						icon: 'none'
					})
				})
			},
			setDefaultAddress(item) {
				item.isDefault = '1'
				editDefault(item).then(res => {
					if (res.code === 200) {
						// 先更新本地数据：将其他地址设为非默认，当前地址设为默认
						this.addressList.forEach(addr => {
							addr.isDefault = addr.id === item.id ? '1' : '0'
						})
						
						uni.showToast({
							title: '修改默认成功',
							icon: 'success'
						})
					} else {
						uni.showToast({
							title: res.msg || '修改失败，请重试',
							icon: 'none'
						})
					}
				}).catch(err => {
					uni.showToast({
						title: '修改失败，请重试',
						icon: 'none'
					})
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.address-list {
		min-height: 100vh;
		background-color: #f5f5f5;

		.select-tip {
			background-color: #f8f8f8;
			padding: 20rpx;
			text-align: center;
			border-bottom: 1px solid #eee;
			
			text {
				font-size: 28rpx;
				color: #666;
				line-height: 1.5;
			}
		}

		.select-indicator {
			position: absolute;
			right: 20rpx;
			top: 50%;
			transform: translateY(-50%);
			
			.select-arrow {
				font-size: 32rpx;
				color: #999;
			}
		}

		.nav-bar {
			display: flex;
			align-items: center;
			height: 44px;
			background-color: #fff;
			padding: 0 15px;
			position: relative;

			.back,
			.more {
				width: 24px;
				height: 24px;

				image {
					width: 100%;
					height: 100%;
				}
			}

			.title {
				flex: 1;
				text-align: center;
				font-size: 16px;
				font-weight: 500;
			}
		}

		.address-items {
			padding: 10px 15px;

			.address-item {
				display: flex;
				flex-direction: column;
				background-color: #fff;
				border-radius: 8px;
				padding: 15px;
				margin-bottom: 10px;
				cursor: pointer;
				transition: all 0.2s ease;

				&:hover {
					box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
				}

				&.select-mode {
					cursor: pointer;
					border: 2rpx solid #e0e0e0;
					
					&:hover {
						background-color: #f8f8f8;
						border-color: #09ab4f;
					}
				}

				.content {
					.user-info {
						margin-bottom: 8px;

						.name {
							font-size: 14px;
							font-weight: 500;
							margin-right: 10px;
						}

						.phone {
							color: #000;
						}
					}

					.address-line {
						font-size: 14px;
						color: #000;
						line-height: 1.4;
						margin-bottom: 15px;
					}
				}

				.item-footer {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding-top: 10px;
					border-top: 1px solid #eee;

					.left {
						display: flex;
						align-items: center;

						radio {
							transform: scale(0.7);
							transform-origin: center;
						}

						.default-text {
							font-size: 12px;
							color: #666;
							margin-left: 5px;
						}
					}

					.edit {
						color: #000;
						font-size: 12px;
						padding-left: 6px;
						padding-right: 6px;
						border: 1px solid #e8ebe8;
					}
				}
			}
		}

		.add-btn {
			position: fixed;
			left: 15px;
			right: 15px;
			bottom: 20px;
			height: 44px;
			line-height: 44px;
			text-align: center;
			background-color: #4cd080;
			color: #fff;
			border-radius: 12px;
			font-size: 16px;
		}
	}
</style>